import {CloseOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Input, message, Popconfirm} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {queryRule, queryStore, addActivity, updateActivity} from './service';
import EditTableStore from "@/pages/PositionManagement/components/EditTableStore";
import styles from "@/global.less";
import Access from '@/components/Access/Access';
import EditGoodsTable from "@/pages/ActivityManagement/MarketActivity/PackageActivity/components/EditGoodsTable";

const TableList = (props) => {
  const activityType = 3; // 套餐活动
  const activitySubType = 5; // 套餐活动
  const goodsCategoryId = '1486699648000204802'; // 可选的商品类目id

  const [loading, setLoading] = useState(false);

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpModalVisible] = useState(false);
  const actionRef = useRef();
  const formRef = useRef();
  const [formValue, setFormValue] = useState({});
  const [storeArr, setStoreArr] = useState([]);
  const [children, setChildren] = useState([]);
  const [Selected, setSelected] = useState([]); // 选定的店铺
  const [storeValue, setStoreValue] = useState([]);
  const [selectedArray, setSelectedArray] = useState([]);
  const [count, setCount] = useState();
  const handleGetStore = async () => {
    const {data} = await queryStore();
    setStoreArr(data);
  };
  const StoreSelect = (record, selected, selectedRows) => {
    if (selected) {
      const list = [record.id];
      setChildren(list.concat(children));
      const selectList = [record];
      setSelected(Selected.concat(selectList));
    } else {
      setChildren(children.filter(id => id !== record.id));
      setSelected(Selected.filter(rec => rec.id !== record.id));
    }
  };
  const StoreSelectChange = (selectedRowKeys, selectedRows, info) => {

  };
  const StoreSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      setChildren(selectedRows.map(record => record.id))
    } else {
      setChildren([])
    }
    setSelected(selectedRows);
  };
  const handleCommissionChild = (value) => {
    const list = JSON.parse(JSON.stringify(storeValue));
    list.map((item) => {
      if (item.storeId === value.id) {
        if (value.id === item.storeId) {
          item.commission = value.commission;
        }
      }
    });
    Selected.map((item) => {
      item.id === value.id
        ? ((item.commission = value.commission), (item.positionId = positionId))
        : null;
    });
    setStoreValue(list);
  };
  const searchStateFun = () => {
    setSelectedArray(Selected);
  };
  useEffect(() => {
    handleGetStore();
    setSelectedGoods([]);
  }, []);

  // 请求创建套餐活动
  const createPackageActivity = (value) => {
    setLoading(true);

    value.stores = Selected.map(store => store.id);
    value.goodsList = SelectedGoods.map(goods => {
      return {
        goodsId: goods.id,
        count: goods.count
      };
    });
    if (value.goodsList.length < 1) {
      message.error('请添加套餐商品!');
      setLoading(false)
      return;
    }
    value.type = activityType;
    value.subType = activitySubType;
    if (value.selectedGoods)
      delete value.selectedGoods;
    addActivity(value).then(res => {
      if (!res) {
        console.log('响应失败');
        return;
      }
      if (res.code === 0) {
        message.info("创建成功");
        setSelectedGoods([]);
        actionRef.current.reload();
      }
      handleModalVisible(false);
    }).finally(() => setLoading(false));
  };
  const updatePackageActivity = (value) => {
    setLoading(true);

    value.stores = Selected.map(store => store.id);
    value.type = activityType;
    value.subType = activitySubType;

    value.goodsList = SelectedGoods.map(goods => {
      return {
        goodsId: goods.id,
        count: goods.count
      };
    });
    if (value.goodsList.length < 1) {
      message.error('请添加套餐商品!');
      setLoading(false)
      return;
    }
    if (value.selectedGoods)
    delete value.selectedGoods;
    value.id = formValue.id;
    updateActivity(value).then(res => {
      if (res && res.code === 0) {
        message.info("更新成功")
        actionRef.current.reload();
      }
      handleUpModalVisible(false);
    }).finally(() => setLoading(false));
  };


  const [SelectedGoods, setSelectedGoods] = useState([]); // 选定的商品
  const handleSelectGoods = (goods, selected = true) => { // 选择商品
    if (selected) { // 选定
      const cacheArr = JSON.parse(JSON.stringify(SelectedGoods));
      let unit = '/';
      if (goods.goodsItemList && goods.goodsItemList[0]) {
        unit = goods.goodsItemList[0].unit;
      }
      cacheArr.push({
        id: goods.id,
        count: 1,
        goodsName: goods.name,
        goodsUnit: unit,
      });
      // cacheArr.push(goods);
      setSelectedGoods(cacheArr);
    }else { // 取消选定
      delSelectedGoods(goods.id);
    }
  };
  // 根据id删除已选定的商品
  const delSelectedGoods = (goodsIds) => {
    if (!Array.isArray(goodsIds)) {
      // eslint-disable-next-line no-param-reassign
      goodsIds = [goodsIds];
    }
    const cacheArr = [];
    for (let i = 0; i < SelectedGoods.length; i++) {
      if (!goodsIds.includes(SelectedGoods[i].id)) {
        cacheArr.push(SelectedGoods[i]);
      }
    }
    setSelectedGoods(cacheArr);
  };
  // 修改商品数量
  const changeGoodsCount = (goodsId, e) => {
    const cacheArr = JSON.parse(JSON.stringify(SelectedGoods));
    const find = cacheArr.find(item => item.id === goodsId);
    if (find) {
      find.count = e.target.value;
    }
    setSelectedGoods(cacheArr);
  };

  const columns = [
    {
      title: '套餐名',
      dataIndex: 'activityName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '活动范围',
      dataIndex: 'allStore',
      hideInSearch: true,
      hideInForm: true,
      valueEnum: {
        true: {
          text: '全场通用',
          status: 'Processing',
        },
        false: {
          text: '部分店铺',
          status: 'Success',
        },
      },
    },
    {
      title: '售价',
      dataIndex: 'activityFull',
      valueType: 'money',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请指定价格',
          },
        ],
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      valueType: 'dateTime',
      sorter: (a, b) => a.startTime - b.startTime,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '开始时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.startTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInSearch: true,
      valueType: 'dateTime',
      sorter: (a, b) => a.endTime - b.endTime,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '结束时间为必填项',
          },
        ],
      },
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.endTime).toLocaleString();
        } else {
          return '-';
        }
      },
    },

    {
      title: '配送周期(月)',
      dataIndex: 'activityDelivTimeType',
      valueType: 'number',
      hideInSearch: true,

      formItemProps: {
        rules: [
          {
            required: true,
            message: '请指定配送周期',
          },
        ],
      },
      renderFormItem: (item,{ type, defaultRender, formItemProps, fieldProps, ...rest },form) => {
        return (
          <Input type={'number'} addonBefore={'每'} addonAfter={'个月'}/>
        );
      },
    },
    {
      title: '总期数',
      dataIndex: 'activityDelivCount',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请指定总期数',
          },
        ],
      },
      renderFormItem: (item,{ type, defaultRender, formItemProps, fieldProps, ...rest },form) => {
        return (
          <Input type={'number'} addonAfter={'期'}/>
        );
      },
    },

    {
      title: '', // 表单中用来占位
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: () => {
        return (<></>);
      }
    },
    {
      title: '选择每期商品',
      dataIndex: 'goodsList',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item,{ type, defaultRender, formItemProps, fieldProps, ...rest },form) => {
        return (
          <EditGoodsTable
            categoryId={goodsCategoryId}
            onSelect={handleSelectGoods}
          />
        );
      },
    },
    {
      title: '已选商品',
      dataIndex: 'selectedGoods',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <div className="selected_div">
            {SelectedGoods.map((item, index) => {
              return (
                <div key={index} className="store_selected">
                  <span>{item.goodsName}</span>
                  <Popconfirm title="确定删除该商品吗?"
                    onConfirm={() => { // 循环匹配当前要删除的商品并删除
                      delSelectedGoods(item.id);
                    }}
                    okText="是" cancelText="否"
                  >
                    <CloseOutlined style={{color: 'red', cursor: 'pointer'}}/>
                  </Popconfirm>
                  <Input onChange={changeGoodsCount.bind(this, item.id)} type={'number'} addonBefore={'数量'} addonAfter={item.goodsUnit} value={item.count}/>
                </div>
              );
            })}
          </div>
        );
      },
    },
    {
      title: '参加店铺',
      dataIndex: 'storeList',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <EditTableStore
            dataSource={storeArr}
            onSelect={StoreSelect}
            onSelectAll={StoreSelectAll}
            onChange={StoreSelectChange}
            handleChildren={children}
            childrenCommission={handleCommissionChild}
            searchState={searchStateFun}
            CommissionState={false}
          />
        );
      },
    },
    {
      title: '已选店铺(默认全场通用)',
      dataIndex: 'selected',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <div className="selected_div">
            {Selected.map((item, index) => {
              return (
                <div key={index} className="store_selected">
                  <span>{item.name}</span>
                  <Popconfirm
                    title="确定删除该店铺吗?"
                    onConfirm={() => {
                      const handleId = JSON.parse(JSON.stringify(children));
                      const list = JSON.parse(JSON.stringify(Selected));
                      list.map((item_, index) => {
                        if (item.id === item_.id) {
                          return list.splice(index, 1);
                        }
                      });
                      handleId.map((item_, index) => {
                        if (item.id === item_) {
                          return handleId.splice(index, 1);
                        }
                      });
                      setSelected(list);
                      setChildren(handleId);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <CloseOutlined style={{color: 'red', cursor: 'pointer'}}/>
                  </Popconfirm>
                </div>
              );
            })}
          </div>
        );
      },
    },
    {
      title: '重复参与次数(每人)',
      dataIndex: 'activityCount',
      valueType: 'number',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '重复参与次数为必填项',
          },
        ],
      },
      renderFormItem: (item,{ type, defaultRender, formItemProps, fieldProps, ...rest },form) => {
        return (
          <Input type={'number'} addonAfter={'次'}/>
        );
      },

    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Access accessKey={"@updatePackageActivity"}>
          <a
            onClick={() => {
              setFormValue(record);
              setChildren(record.stores);
              if (!record.stores) {
                record.stores = [];
              }
              const selectStores = storeArr.filter(store => {
                return record.stores.includes(store.id) // 回显店铺选定
              });
              setSelected(selectStores);
              setSelectedGoods([]); // 清空
              if (!record.goodsList) {
                record.goodsList = [];
              }

              const cacheArr = record.goodsList.map(activityGoods => {
                return {
                  id: activityGoods.goodsId,
                  count: activityGoods.count,
                  goodsName: activityGoods.goodsName,
                  goodsUnit: activityGoods.goodsUnit,
                };
              });
              setSelectedGoods(cacheArr);
              handleUpModalVisible(true);
            }}
          >
            修改
          </a>
        </Access>

      ),
    },
  ];

  // 新建弹框的footer
  const renderFooter = () => {
    return (
      <>
        {/*<div style={{*/}
        {/*  'color': 'red',*/}
        {/*  'textAlign':'left',*/}
        {/*}}>*/}
        {/*  * 互斥规则说明: 参加当前活动时检查互斥活动列表中的活动是否已经参与(只要有一个互斥活动的参与次数超出限制就不能再参加本活动)*/}
        {/*</div>*/}
        {/*<div style={{*/}
        {/*  'color': 'red',*/}
        {/*  'textAlign':'left',*/}
        {/*}}>*/}
        {/*  * 关联赠品说明: 所选赠品在其他类型店铺中的商品库存(只在领取赠品时生效,不设置表示只能在有所选赠品的店铺领取)*/}
        {/*</div>*/}
      </>

    );
  };

  return (
    <PageContainer>
      {/*数据列表*/}
      <ProTable
        headerTitle="套餐活动列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        scroll={{x: 1200}} bordered
        toolBarRender={() => [
          <Access accessKey={"@newPackageActivity"}>
            <Button type="primary" onClick={() => {
              setSelected([]);
              setChildren([]);
              setFormValue({});
              setSelectedGoods([]); // 清空数据
              handleModalVisible(true);
            }}>
              <PlusOutlined/> 新建
            </Button>
          </Access>
          ,
        ]}
        request={(params, sorter, filter) =>
          queryRule({...params, sorter, filter, type: activityType,subType: activitySubType, withGoods: true})
        }
        postData={(payload) => {
          const {list, total} = payload;
          setCount(total);
          return list || [];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: true,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      {/*新建弹框form*/}
      <CreateForm
        title={'新建套餐'}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        width={1200}
        footer={renderFooter()}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            createPackageActivity(value);
          }}
          loading={loading}
          rowKey="id"
          bordered
          type="form"
          formRef={formRef}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={columns}
        />
      </CreateForm>
      {/*更新弹框form*/}
      <CreateForm
        title={'更新套餐'}
        onCancel={() => handleUpModalVisible(false)}
        modalVisible={updateModalVisible}
        width={1200}
        footer={renderFooter()}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            updatePackageActivity(value);
          }}
          loading={loading}
          rowKey="id"
          bordered
          type="form"
          formRef={formRef}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
          columns={columns}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
